package com.ellricky.baselib.widget;

import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AnimationSet;


import com.ellricky.baselib.R;

import java.util.Locale;

/**
 * colorful arc progress bar
 * Created by shinelw on 12/4/15.
 */
public class IntegralProgressBar extends View {

    private float centerX;  //圆心X坐标
    private float centerY;  //圆心Y坐标


    // 背景
    private Paint circleBgPaint;
    private int circleBgColor;
    private float circleBgRadius;


    // 指示标
    private Paint circleBgPaint2;
    private int circleBgColor2;
    private float circleBgRadius2;
    private Path pointerPath = new Path();


    // 进度
    private RectF bgRect;
    private float startAngle = 135;

    private Paint allArcPaint;
    private int allArcColor;
    private float allArcWidth = dipToPx(2);
    private float allArcAngle;

    private Paint pBarPaint;
    private int[] pBarColors = new int[]{Color.GREEN, Color.YELLOW, Color.RED, Color.RED};
    private float pBarWidth = dipToPx(10);

    // 文本
    private Paint textPaint;
    private float curValues = 0;
    private float maxValues;
    private int textColor;
    private float textSize = dipToPx(60);

    private Paint labelPaint;
    private String label;
    private int labelColor;
    private float labelTextSize = dipToPx(15);


    private int viewWH;


    private ValueAnimator progressAnimator;
    private AnimationSet animationSet;


    private PaintFlagsDrawFilter mDrawFilter;
    private SweepGradient sweepGradient;
    private Matrix rotateMatrix;

    private float currentAngle = 0;
    private float lastAngle;
    private float curPointerAngle = 0;


    // sweepAngle / maxValues 的值
    private float k;

    public IntegralProgressBar(Context context) {
        super(context, null);
        initView();
    }

    public IntegralProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
        initCofig(context, attrs);
        initView();
    }

    public IntegralProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initCofig(context, attrs);
        initView();
    }


    /**
     * 初始化布局配置
     *
     * @param context
     * @param attrs
     */
    private void initCofig(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IntegralProgressBar);

        circleBgColor = a.getColor(
                R.styleable.IntegralProgressBar_bottom_circle_color,
                Color.TRANSPARENT
        );
        circleBgRadius = a.getDimension(
                R.styleable.IntegralProgressBar_bottom_circle_radius,
                dipToPx(70)
        );

        circleBgColor2 = a.getColor(
                R.styleable.IntegralProgressBar_center_circle_color,
                Color.TRANSPARENT
        );

        circleBgRadius2 = a.getDimension(
                R.styleable.IntegralProgressBar_center_circle_radius,
                dipToPx(50)
        );

        startAngle = a.getInteger(R.styleable.IntegralProgressBar_start_angle, 0);
        allArcAngle = a.getInteger(R.styleable.IntegralProgressBar_total_angle, 360);

        allArcColor = a.getColor(R.styleable.IntegralProgressBar_pBar_sec_color, Color.WHITE);
        allArcWidth = a.getDimension(R.styleable.IntegralProgressBar_pBar_sec_width, dipToPx(3));


        int color1 = a.getColor(R.styleable.IntegralProgressBar_pBar_start_color, Color.GREEN);
        int color2 = a.getColor(R.styleable.IntegralProgressBar_pBar_end_color, color1);
        pBarColors = new int[]{color1, color2, color2, color2};
        pBarWidth = a.getDimension(R.styleable.IntegralProgressBar_pBar_width, dipToPx(20));


        textColor = a.getColor(R.styleable.IntegralProgressBar_integral_text_color, Color.BLACK);
        textSize = a.getDimension(R.styleable.IntegralProgressBar_integral_text_size, dipToPx(80));

        curValues = a.getFloat(R.styleable.IntegralProgressBar_integral_current_value, 0);
        maxValues = a.getFloat(R.styleable.IntegralProgressBar_integral_max_value, 1000);

        label = a.getString(R.styleable.IntegralProgressBar_integral_label);
        labelColor = a.getColor(R.styleable.IntegralProgressBar_integral_label_color, Color.BLACK);
        labelTextSize = a.getDimension(
                R.styleable.IntegralProgressBar_integral_label_size, dipToPx(15));
        if (TextUtils.isEmpty(label)) {
            label = "总积分";
        }


        viewWH = (int) (circleBgRadius * 2 + allArcWidth + pBarWidth);

        setMaxValues(maxValues);
        setCurrentValues(curValues);

        a.recycle();

    }


    private void initView() {
        this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        //圆心
        centerX = viewWH / 2;
        centerY = viewWH / 2;

        circleBgPaint = new Paint();
        circleBgPaint.setAntiAlias(true);
        circleBgPaint.setStyle(Paint.Style.FILL);
        circleBgPaint.setColor(circleBgColor);
        circleBgPaint.setStrokeCap(Paint.Cap.ROUND);

        circleBgPaint2 = new Paint();
        circleBgPaint2.setAntiAlias(true);
        circleBgPaint2.setStyle(Paint.Style.FILL);
        circleBgPaint2.setColor(circleBgColor2);
        circleBgPaint2.setStrokeCap(Paint.Cap.ROUND);
        initPointerPath();


        //整个弧形
        allArcPaint = new Paint();
        allArcPaint.setAntiAlias(true);
        allArcPaint.setStyle(Paint.Style.STROKE);
        allArcPaint.setStrokeWidth(allArcWidth);
        allArcPaint.setColor(allArcColor);
        allArcPaint.setStrokeCap(Paint.Cap.ROUND);

        //弧形的矩阵区域
        bgRect = new RectF();
        bgRect.top = centerY - circleBgRadius;
        bgRect.left = centerX - circleBgRadius;
        bgRect.right = centerX + circleBgRadius;
        bgRect.bottom = centerY + circleBgRadius;

        //当前进度的弧形
        pBarPaint = new Paint();
        pBarPaint.setAntiAlias(true);
        pBarPaint.setStyle(Paint.Style.STROKE);
        pBarPaint.setStrokeCap(Paint.Cap.ROUND);
        pBarPaint.setStrokeWidth(pBarWidth);
        pBarPaint.setColor(Color.YELLOW);


        //内容显示文字
        textPaint = new Paint();
        textPaint.setTextSize(textSize);
        textPaint.setColor(textColor);
        textPaint.setTextAlign(Paint.Align.CENTER);

        //标签
        labelPaint = new Paint();
        labelPaint.setTextSize(labelTextSize);
        labelPaint.setColor(labelColor);
        labelPaint.setTextAlign(Paint.Align.CENTER);


        mDrawFilter = new PaintFlagsDrawFilter(
                0,
                Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG
        );

        sweepGradient = new SweepGradient(centerX, centerY, pBarColors, null);
        rotateMatrix = new Matrix();

    }


    private void initPointerPath() {
        pointerPath.reset();
        double angel = 1 * Math.PI / 180;
        float trivh = dipToPx(3);  // 三角垂直平分线长度
        float dx = (float) (circleBgRadius2 * Math.sin(angel));
        float dy = (float) (circleBgRadius2 * Math.cos(angel));
        float pointerY = dy + trivh;

        pointerPath.moveTo(centerX - dx, centerY - dy);
        pointerPath.lineTo(centerX, centerY - pointerY);
        pointerPath.lineTo(centerX + dx, centerY - dy);

        RectF rect = new RectF(
                centerX - circleBgRadius2,
                centerY - circleBgRadius2,
                centerX + circleBgRadius2,
                centerY + circleBgRadius2
        );
        pointerPath.addArc(rect, 100, 358);


    }


    //必须重写该方法，否则在xml文件中定义warp_content与match_parent效果相同
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(viewWH, viewWH);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        //抗锯齿
        canvas.setDrawFilter(mDrawFilter);

        // 背景圆
        canvas.drawCircle(centerX, centerY, circleBgRadius, circleBgPaint);

        // 指示标圆
        circleBgPaint2.setShadowLayer(10, 5, 5, Color.parseColor("#F1F1F1"));
        /*canvas.drawCircle(centerX, centerY, circleBgRadius2, circleBgPaint2);*/
        canvas.rotate(-135 + curPointerAngle, centerX, centerY);
        canvas.drawPath(pointerPath, circleBgPaint2);
        canvas.restore();

        //整个弧
        canvas.drawArc(bgRect, startAngle, allArcAngle, false, allArcPaint);

        //设置渐变色
        rotateMatrix.setRotate(130, centerX, centerY);
        sweepGradient.setLocalMatrix(rotateMatrix);
        pBarPaint.setShader(sweepGradient);

        //当前进度
        canvas.drawArc(bgRect, startAngle, currentAngle, false, pBarPaint);

        canvas.drawText(String.format(Locale.CHINA, "%.0f", curValues),
                centerX, centerY + textSize / 3, textPaint
        );

        canvas.drawText(label, centerX, centerY + circleBgRadius2 / 2, labelPaint);


        postInvalidate();

    }


    /**
     * 设置当前值
     *
     * @param targetValue
     */
    public void setCurrentValues(float targetValue) {
        if (targetValue > maxValues) {
            targetValue = maxValues;
        }
        if (targetValue < 0) {
            targetValue = 0;
        }
        /* this.curValues = targetValue;*/
        lastAngle = currentAngle;
        setAnimation(lastAngle, targetValue * k);
    }

    /**
     * 设置最大值
     *
     * @param maxValues
     */
    public void setMaxValues(float maxValues) {
        this.maxValues = maxValues;
        k = allArcAngle / maxValues;
    }


    /**
     * 为进度设置动画
     *
     * @param last
     * @param current
     */
    private void setAnimation(float last, float current) {
        ValueAnimator progressAnimator = ValueAnimator.ofFloat(last, current);
        progressAnimator.setTarget(currentAngle);
        progressAnimator.setDuration(1500);
        progressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                currentAngle = (float) animation.getAnimatedValue();
                curValues = currentAngle / k;
            }

        });


        ValueAnimator pointerAnim = ValueAnimator.ofFloat(0, current);
        pointerAnim.setDuration(2500);
        pointerAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                curPointerAngle = (float) animation.getAnimatedValue();
            }

        });


        AnimatorSet animSet = new AnimatorSet();
        animSet.playTogether(progressAnimator, pointerAnim);
        animSet.start();

    }


//    private void createPointerAnim() {
//        ValueAnimator animator = ValueAnimator.ofFloat(last, current);
//        animator.setDuration(length);
//        animator.setStartDelay(500);
//        animator.setTarget(currentAngle);
//
//        animator.setInterpolator(new DecelerateInterpolator() {
//
//        });
//
//        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//
//            @Override
//            public void onAnimationUpdate(ValueAnimator animation) {
//                currentAngle = (float) animation.getAnimatedValue();
//
//            }
//
//        });
//        progressAnimator.start();
//    }


    private void setPointerAnimation(float last, float current, int length) {

    }


    /**
     * dip 转换成px
     *
     * @param dip
     * @return
     */
    private int dipToPx(float dip) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1));
    }

    /**
     * 得到屏幕宽度
     *
     * @return
     */
    private int getScreenWidth() {
        WindowManager windowManager = (WindowManager) getContext().getSystemService(
                Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }
}




